package si.dejan.picflip.model
{
	import com.adobe.webapis.flickr.FlickrError;
	import com.adobe.webapis.flickr.FlickrService;
	import com.adobe.webapis.flickr.PagedPhotoList;
	import com.adobe.webapis.flickr.Photo;
	import com.adobe.webapis.flickr.events.FlickrResultEvent;
	
	import mx.controls.Alert;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;

	/**
	 * Takes care of searching
	 * Holds PagedPhotoList as data
	 */
	public class SearchProxy extends Proxy implements IProxy
	{
		public static const NAME:String = "FlickrProxy";

		public static const SEARCH:String = "searchdone";

		private var flickr:FlickrService;
		private var currentIndex:int = -20;

		private var _stackSize:int = 20;

		public function SearchProxy(api:String, stackSize:int = 20)
		{
			super(NAME);

			flickr = new FlickrService(api);
			_stackSize = stackSize;
		}

		private function showAlert(error:Object):void
		{
			Alert.show("Nek error", "Error");
		}

		public function search(text:String):void
		{
			flickr.addEventListener(FlickrResultEvent.PHOTOS_SEARCH, handleSearchComplete);
			flickr.photos.search("", text, "any", text);
		}

		private function handleSearchComplete(event:FlickrResultEvent):void
		{
			data = event.data.photos;
			if(event.data is FlickrError)
				showAlert(event.data);
			else
				sendNotification(SEARCH, event.data.photos);
		}

		public function getRecent():void
		{
			flickr.addEventListener(FlickrResultEvent.PHOTOS_GET_RECENT, handleSearchComplete);
			flickr.photos.getRecent();
		}

		/** Returns the next set of images */
		public function getNextSet():Array
		{
			currentIndex += _stackSize;
			var toReturn:Array = allPhotos.slice(currentIndex, currentIndex + _stackSize); 
			return toReturn;
		}

		/** Returns previous set of images */
		public function getPreviousSet():Array
		{
			currentIndex -= _stackSize;
			if(currentIndex < 0)
				currentIndex = 0;

			return allPhotos.slice(currentIndex, currentIndex + _stackSize);
		}

		public function getPhotosUrl(photos:Array):Array
		{
			var urlPhotos:Array = new Array();

			for each(var photo:Photo in photos)
				urlPhotos.push("http://static.flickr.com/" + photo.server + '/' + photo.id + '_' + photo.secret + '_m.jpg');

			return urlPhotos;
		}

		public function getFullImageUrl(url:String):String
		{
			return url.replace("_m", "");
		}

		private function get allPhotos():Array
		{
			return data.photos;
		}
	}
}